﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GenericControlsWinForm
{
    public class CPFTextBox : TextBox
    {
        public CPFTextBox()
        {
            //Evento que vai verificar se a letra pode ser inserida
            this.KeyDown += new KeyEventHandler(CPFTextBox_KeyDown);
            //Evento que vai formatar a string
            this.KeyUp += new KeyEventHandler(CPFTextBox_KeyUp);
            this.MaxLength = 14;
            this.Width = 100;
        }

        void CPFTextBox_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                string texto = this.Text.Replace(".", "").Replace("-", "");

                if (texto.Length > 3)
                {
                    texto = texto.Insert(3, ".");
                    if (texto.Length > 7)
                    {
                        texto = texto.Insert(7, ".");
                        if (texto.Length > 11)
                            texto = texto.Insert(11, "-");
                    }
                    this.Text = texto;
                    this.SelectionStart = this.Text.Length;
                }
            }
            catch (Exception)
            {
                throw new Exception("Erro no componente CPF.");
            }
        }

        void CPFTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (!CommomValidator.KeyIsNumber(e.KeyCode) && e.KeyCode != Keys.Tab)
                    e.Handled = true;
            }
            catch (Exception)
            {
                throw new Exception("Erro no componente CPF.");
            }
        }
    }
}
